package com.dyz.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FindDuplicate287 {
    public static void main(String[] args) {
        int [] nums = new int[]{1,3,4,2,2};
        int duplicate2 = new FindDuplicate287().findDuplicate2(nums);
    }
    public int findDuplicate(int[] nums) {
        if(nums==null || nums.length==0){return -1;}
        Map<Integer, Integer> map = new HashMap<>();
        for(int num:nums){
            map.put(num, map.getOrDefault(num, 0)+1);
        }
        Set<Map.Entry<Integer, Integer>> entries = map.entrySet();
        for(Map.Entry<Integer, Integer> entry:entries){
            if (entry.getValue()>=2){
                return entry.getKey();
            }
        }
        return -1;
    }

    //快慢指针
    public int findDuplicate1(int[] nums) {
        int slow = 0, fast = 0;
        do {
            slow = nums[slow];
            fast = nums[nums[fast]];
        } while (slow != fast);
        slow = 0;
        while (slow != fast) {
            slow = nums[slow];
            fast = nums[fast];
        }
        return slow;
    }
    //二分法
    public int findDuplicate2(int[] nums) {
        int n = nums.length;
        int l = 1, r = n - 1, ans = -1;
        while (l <= r) {
            int mid = (l + r) >> 1;
            int cnt = 0;
            for (int i = 0; i < n; ++i) {
                if (nums[i] <= mid) {
                    cnt++;
                }
            }
            if (cnt <= mid) {
                l = mid + 1;
            } else {
                r = mid - 1;
                ans = mid;
            }
        }
        return ans;
    }
}
